package com.demo.com.highavailability.monitor;

import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ThreadMonitor {

    private static final Map<Long, ThreadHealthStats> threadStats = new ConcurrentHashMap<>();

    public static void startBusinessProcess() {
        long threadId = Thread.currentThread().getId();
        threadStats.put(threadId, new ThreadHealthStats(threadId));
    }

    public static void endBusinessProcess() {
        long threadId = Thread.currentThread().getId();
        threadStats.remove(threadId);
    }

    public static boolean isHealthy() {
        long threadId = Thread.currentThread().getId();
        ThreadHealthStats stats = threadStats.get(threadId);
        if (stats == null) return true;
        return stats.getErrorRate() < 0.1 &&
               stats.getAvgProcessTime() < 1000 &&
               stats.getTimeoutCount() < 3;
    }

    @Data
    private static class ThreadHealthStats {
        private final long threadId;
        private int errorCount = 0;
        private int successCount = 0;
        private int timeoutCount = 0;
        private long totalProcessTime = 0;

        public double getErrorRate() {
            int total = errorCount + successCount;
            return total == 0 ? 0 : (double) errorCount / total;
        }

        public long getAvgProcessTime() {
            int total = errorCount + successCount;
            return total == 0 ? 0 : totalProcessTime / total;
        }
    }
}